﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using SalesSys.BLL;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;

namespace SalesSys.WebCore
{

    /// <summary>
    /// 站点配置，会读取标记为Display的属性,系统启动时需进行init初始化
    /// </summary>
    public class SiteConfig
    {
        
        [Display(Description = "默认页码")]
        public readonly int PageNum = 1;
        [Display(Description = "默认分页大小")]
        public readonly int PageSize = 2;
        [Display(Description = "默认密码")]
        public readonly string EmployeeDefPwd = "123456";
        [Display(Description = "超级管理员id")]
        public readonly Guid SuperAdminId = Guid.Parse("010424ba-2409-465c-92b8-ecbaadb1d010");

        [Display(Description = "全局默认图片,用于图片加载失败时显示")]
        public readonly string DefaultImg = "/img/default.jpg";
        
        #region init
        static IBaseBLL<SysConfig, Guid> setting { get { return new BaseBLL<SysConfig, Guid>(); } }
        static bool isInit = false;

        /// <summary>
        /// 初始化站点配置项
        /// </summary>
        /// <param name="isReInit"></param>
        /// <returns></returns>
        public static SiteConfig Init(bool isReInit = false)
        {
            if (!isReInit && isInit)
            {
                throw new ArgumentException("不能重复初始化");
            }
            Log.m.Info("SiteConfig初始化开始");
            DbGet();
            isInit = true;
            Log.m.Info("SiteConfig初始化结束");
            return configInfo;
        }

        /// <summary>
        /// 插入初始化数据，
        /// </summary>
        /// <param name="isDrop">未true则直接删除已有数据，否则如果存在数据则插入失败</param>
        internal static void Create(bool isDrop = false,
            Func<List<SysConfig>, IEnumerable<SysConfig>> dataHandleFun = null)
        {
            var info = setting.GetList(1, 999);
            if (isDrop)
            {
                if (info.Length > 0)
                {
                    //   setting.Delete(info);
                }
            }
            else
            {
                if (info.Length > 0)
                {
                    throw new ArgumentException("初始化数据已存在，请移除后再初始化");
                }
            }
            List<SysConfig> list = new List<SysConfig>();
            var fields = typeof (SiteConfig).GetFields();
            var model = new SiteConfig();
            foreach (var item in fields)
            {
                var attrs = item.GetCustomAttributes<DisplayAttribute>();
                if (attrs == null || attrs.Count() < 1)
                    continue;
                var attr = attrs.First();
                var menu = new SysConfig();
                menu.Remarks = attr.Description;
                menu.Key = item.Name;
                menu.Group = attr.GroupName ?? "";
                //
                menu.Value = Convert.ToString(item.GetValue(model));
                list.Add(menu);
            }
            IEnumerable<SysConfig> dataList = dataHandleFun == null ? list : dataHandleFun(list);
            setting.Create(dataList);
        }

        static void DbGet()
        {
            var config = new SiteConfig();
            var dic = setting.GetList(1, 999).ToDictionary(p =>p.Group+"__"+ p.Key);
            var fields = typeof(SiteConfig).GetFields();
            foreach (var item in fields)
            {
                var attrs = item.GetCustomAttributes<DisplayAttribute>();
                if (attrs == null || attrs.Count() < 1)
                    continue;
                SysConfig tmp = null;
                if (!dic.TryGetValue(item.Name, out tmp))
                {

                    Log.m.Warn("数据库配置初始化SiteSetting错误，无法找到指定的配置项" + item.Name);
                    throw new ArgumentException("数据库配置初始化SiteSetting错误，无法找到指定的配置项:" + item.Name);
                }
                item.SetValue(config, tmp.Value.ConvertTo(item.FieldType));
            }
            configInfo = config;
        }
        static SiteConfig configInfo = new SiteConfig();
        public static SiteConfig ConfigInfo
        {
            get { return configInfo; }
        }
        #endregion

    }


}
